package com.atmilan.quartz.sync.push.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.atmilan.quartz.model.dto.buyer.BuyerOrderDTO;
import com.atmilan.quartz.model.entity.buyer.BuyerProductSku;
import com.atmilan.quartz.model.entity.sync.SyncOrderProduct;
import com.atmilan.quartz.model.entity.sync.SyncOrderStore;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerProductSkuService;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerService;
import com.atmilan.quartz.sync.push.service.OrderPushService;
import com.atmilan.quartz.sync.service.ISyncOrderProductService;
import com.atmilan.quartz.sync.service.ISyncOrderStoreService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * x
 *
 * @author muyu.myw
 * @date 2020/10/10 14:05
 */
@Slf4j
@Service
public class OrderPushServiceImpl implements OrderPushService {
    @Autowired
    ISyncOrderStoreService syncOrderStoreService;
    @Autowired
    ISyncOrderProductService syncOrderProductService;
    @Autowired
    IBuyerProductSkuService buyerProductSkuService;
    @Autowired
    IBuyerService buyerService;
    
    @Value("${task.order.push:false}")
    private final Boolean orderPush = false;
    
    @Override
    public String pushOrder(SyncOrderStore orderStore) {
        if(orderStore == null){
            return null;
        }
        String orderNo =  orderStore.getOuterOrderNo();

        try{
            List<SyncOrderProduct> list = syncOrderProductService.list(Wrappers.<SyncOrderProduct>lambdaQuery().eq(SyncOrderProduct::getOuterOrderNo,orderNo));
            if(CollectionUtils.isNotEmpty(list)){
                BuyerOrderDTO order = new BuyerOrderDTO();
                order.setOrderSn(orderStore.getOuterOrderNo());
                order.setAddress(orderStore.getAddress());
                order.setConsignee(orderStore.getConsignee());
                order.setMobile(orderStore.getPhone());
                order.setRegion(orderStore.getRegion());
                order.setShippingType(orderStore.getShippingType());
                order.setTotal(orderStore.getPayPrice().intValue());

                List<BuyerOrderDTO.Goods> goodsList = new ArrayList<BuyerOrderDTO.Goods>();
                for(SyncOrderProduct product:list){
                    // 拆单规则，取buyer sku，凑库存
                    List<BuyerProductSku> skuList = buyerProductSkuService.list(Wrappers.<BuyerProductSku>lambdaQuery()
                            .eq(BuyerProductSku::getGoodsId,product.getProductId())
                            .eq(BuyerProductSku::getSuk,product.getSuk())
                            .gt(BuyerProductSku::getStock,0)
                            .ne(BuyerProductSku::getUpdateFlag,0)
                            .orderByDesc(BuyerProductSku::getStock)
                    );
                    // todo: 没有可用的sku, 订单处理失败 ？
                    if(CollectionUtils.isEmpty(skuList)){
                        log.error("找不到可用的sku! orderNo: {}, product: {} ",orderNo,product.getProductId());
                    }
                    int totalQty = product.getQty();
                    for(BuyerProductSku sku:skuList){
                        BuyerOrderDTO.Goods goods = new BuyerOrderDTO.Goods();
                        goods.setPrice(product.getPrice().intValue());
                        goods.setSkuId(sku.getSkuId());
                        goods.setStockArea(sku.getStock());
                        goods.setQihuo(sku.getQihuo());
                        goods.setAttr(sku.getSuk());
                        if(totalQty>sku.getStock()){
                            goods.setQty(sku.getStock());
                        }else{
                            goods.setQty(totalQty);
                        }
                        totalQty-=goods.getQty();
                        goodsList.add(goods);
                        if(totalQty<=0){
                            break;
                        }
                    }
                    // todo: 如果库存不够怎么办？
                    if(totalQty>0){
                        log.error("商品库存不够! orderNo: {}, product: {}",orderNo,product.getProductId());
                    }
                }
                order.setGoodsList(goodsList);
                try {
                    log.info(new ObjectMapper().writeValueAsString(order));
                } catch (JsonProcessingException e) {
                    log.error("writeString error! orderNo:{}, e:",orderNo,e);
                }
                // 分单完成，先不推订单测试一下
                if(orderPush){
                    // 推订单, 要解析 ret 处理返回失败的情况
                    String ret = buyerService.pushOrder(order);
                    log.warn(ret);
                    return ret;
                }
            }
        }catch (Exception e){
            log.error("push order failed! orderNo: {} ex:",orderNo,e);
        }
        return null;
        // 一家有多个供应商商品的情况，没法解决了
    }
}
